﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using NLog;
using Vue.Admin.Common;
using Vue.Admin.Models;
using Vue.Admin.Models.Dto;
using Vue.Admin.Models;
using Vue.Admin.Tools;

namespace Vue.Admin.Api.Controllers
{
    /// <summary>
    /// 登录授权
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly DBContext _dbContext;
        private readonly JwtSettings _jwtSettings;
        private Logger _logger = LogManager.GetCurrentClassLogger();

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        /// <param name="jwtSettings">jwt配置</param>
        /// <param name="logger">nlog日志</param>
        public AccountController(DBContext dbContext, IOptions<JwtSettings> jwtSettings)
        {
            _dbContext = dbContext;
            _jwtSettings = jwtSettings.Value;
        }
        #endregion

        #region 登录
        /// <summary>
        /// 登录接口（获取当前用户信息和token）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> Login([FromBody] LoginDto dto)
        {
            if (ModelState.IsValid)
            {
                EBaseEmp emp = await _dbContext.EBaseEmp.FirstOrDefaultAsync(x => x.FuserName == dto.username && x.Fpwd == MD5Tools.MD5Hash(dto.userpwd).ToLower()); 
                if (emp != null)
                {
                    List<int> roleids = (from a in _dbContext.ESyEmpRoleMap
                                         join b in _dbContext.EBaseEmp on a.FempId equals b.Fid
                                             into table
                                         from t in table.DefaultIfEmpty()
                                         select new { a.FroleId, a.FempId }).Where(x => x.FempId == emp.Fid).Select(x => x.FroleId) as List<int>;

                    List<string> roleNames = (from a in _dbContext.ESyEmpRoleMap
                                                     join b in _dbContext.EBaseEmp on a.FempId equals b.Fid
                                                     into table
                                                     from t in table.DefaultIfEmpty()
                                                     join c in _dbContext.ESysRoles on a.FroleId equals c.Fid
                                                     into dd
                                                     from d in dd.DefaultIfEmpty()
                                                     select new { d.Fname, t.Fid }).Where(x => x.Fid == emp.Fid).Select(x => x.Fname) as List<string>;
                    UserDataDto userInfo = new UserDataDto
                    {
                        UserId = emp.Fid,
                        UserName = emp.FuserName,
                        UserRoleIds = string.Join(',', roleids),
                        UserRoleName = string.Join(',', roleNames)
                    };
                    var token = JwtHelper.CreatToken(_jwtSettings, userInfo);
                    //存储到Redis代码
                    //
                    return new Result
                    {
                        Code = 1,
                        Message = "登录成功",
                        Object = userInfo,
                        ExtendObject = new { Access_Token = token }
                    };
                }
                else
                {
                    return new Result { Code = 0, Message = "账号或密码错误", Object = null };
                }

            }
            else
            {
                return new Result { Code = -1, Message = "验证不通过" };
            }
        }
        #endregion

        #region 更改密码
        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="changePassWordto">更改密码实体</param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public async Task<Result> ChangePassWord(ChangePassWordDto changePassWordto)
        {
            if (!ModelState.IsValid)
            {
                return new Result() { Code = -1, Message = "实体验证失败" };
            }
            try
            {
                var emp = _dbContext.EBaseEmp.FirstOrDefault(x => x.FuserName == changePassWordto.UserName);
                if (emp != null)
                {
                    emp.Fpwd = MD5Tools.MD5Hash(changePassWordto.PassWord);
                    _dbContext.EBaseEmp.Update(emp);
                    await _dbContext.SaveChangesAsync();
                    return new Result() { Code = 1, Message = "密码重置成功" };
                }
                return new Result {Code=0, Message="找不到用户"};
                
            }
            catch (Exception e)
            {
                _logger.Error(e, "发生异常");
                return new Result() { Code = 0, Message = $"密码重置出错,错误信息如下:{e.Message}" };
            }
        }
        #endregion

    }

}